package com.lightsh.webview;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SimpleWebView extends WebView{
	private static final String TAG = "SimpleWebView";
	
	public SimpleWebView(Context context, AttributeSet attrs){
		super(context, attrs);
	}
	
	public void startTest(){
		enableJs();
		loadData("", "text/html", "utf-8");
		loadUrl("javascript:window.Client.fillProfileSuccess();");
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void enableJs(){
		getSettings().setJavaScriptEnabled(true);
		
		// FIXME test 360
		addJavascriptInterface(new ClientObject(), "Client");
		
		setWebViewClient(new MyWebViewClient());
		
		
		// 适应屏幕
		getSettings().setUseWideViewPort(true);
		getSettings().setLoadWithOverviewMode(true);
		
		// 缩放
		getSettings().setSupportZoom(true);
		getSettings().setBuiltInZoomControls(true);
	}
	
	protected class ClientObject{
		@JavascriptInterface
		public void fillProfileSuccess(){
			Log.e(TAG, "fillProfileSuccess----------------");
			AlertDialog.Builder builder = new AlertDialog.Builder(SimpleWebView.this.getContext());
			builder.setTitle("弹出的title");
			builder.setPositiveButton("hello", null);
			builder.show();
		}
	}
	
	private class MyWebViewClient extends WebViewClient{

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.e(TAG, "onPageStarted : " + url);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			Log.e(TAG, "onPageFinished : " + url);
		}
	}
	
	public boolean handleBackPressed(){
		if(canGoBack()){
			goBack();
			return true;
		}
		return false;
	}
}
